<script setup lang='ts'>
defineOptions({
  name: "Recharge"
});
import { reactive, ref } from "vue";
import { pay_request, getOrderDetail } from "@/api/user";
import { message } from "@/utils/message";
const money_form = reactive({
  num: null,
  pay_type: "",
});
const pay_src = ref("");
const pay_url = ref("");
const pay_dialog = ref(false);
const topay = async () => {
  let res = await pay_request({ pay_price: money_form.num, pay_type: money_form.pay_type });
  console.log('提交充值', res);
  if (res.data.data.type == 'html') {
    pay_url.value = res.data.data.html;
    pay_dialog.value = true;
    console.log('订单信息', res.data.trade_id);
    //查询订单信息
    check_order(res.data.trade_id)
  } else {
    pay_src.value = res.data.data.img;
  }
};
const check_order = async (id, maxRetries = 5, retryInterval = 3000) => {
  let retries = 0;
  const checkStatus = async () => {
    const res = await getOrderDetail(id);
    console.log(res.data.data.trade_state, "订单信息");
    if (res.data.data.trade_state === 1) {
      pay_dialog.value = false;
      message("支付成功", { type: 'success' });
      return;
    }
    // 如果达到最大重试次数，停止重试
    if (retries >= maxRetries) {
      console.error("达到最大重试次数，订单状态仍不是1");
      return;
    }
    // 未达到最大重试，等待一段时间后重试
    retries++;
    setTimeout(checkStatus, retryInterval);
  };
  checkStatus();
};

</script>

<template>
  <div class="main">账户充值
    <el-form label-width="auto" :model="money_form" style="max-width: 600px">
      <el-form-item label="充值金额">
        <el-input v-model="money_form.num" type="number" width="20px" placeholder="充值金额" />
      </el-form-item>
      <el-form-item label="充值方式">
        <el-radio-group v-model="money_form.pay_type">
          <el-radio value="0" border>支付宝支付</el-radio>
          <el-radio value="1" border>微信支付</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="扫码支付" v-if="pay_src != ''">
        <el-image style="width: 100px; height: 100px" :src="pay_src" />
      </el-form-item>
      <el-button @click="topay">提交订单</el-button>
    </el-form>
    <el-dialog title='支付' v-model="pay_dialog" style="width: 90%;height:1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100% ;height:800px"></iframe>
    </el-dialog>
  </div>
</template>

<style lang='scss' scoped>
.main{
  background-color: white;
  padding: 20px
}

</style>
